package com.xhl.shiro.oauth2;

import com.gitee.fastmybatis.core.query.Query;
import com.gitee.fastmybatis.core.support.IService;
import com.xhl.shiro.constant.ShiroConstant;
import com.xhl.shiro.modules.admin.entity.SysMenuEntity;
import com.xhl.shiro.modules.admin.entity.SysUserEntity;
import com.xhl.shiro.modules.admin.entity.SysUserTokenEntity;
import com.xhl.shiro.modules.admin.mapper.SysMenuMapper;
import com.xhl.shiro.modules.admin.mapper.SysUserMapper;
import com.xhl.shiro.modules.admin.mapper.SysUserTokenMapper;
import com.xhl.shiro.modules.admin.service.SysMenuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("shiroService")
public class ShiroService implements IService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserTokenMapper sysUserTokenMapper;


    /**
     * 获取当前用户所有的权限
     */
    public Set<String> getUserPermissions(long userId){
        List<String> permsList;

        //系统管理员，拥有最高权限
        if(userId == ShiroConstant.SUPER_ADMIN){
            List<SysMenuEntity> menuList = sysMenuMapper.list(new Query());
            permsList = new ArrayList<>(menuList.size());
            for(SysMenuEntity menu : menuList){
                permsList.add(menu.getPerms());
            }
        }else{
            permsList = sysUserMapper.queryAllPerms(userId);
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StringUtils.isBlank(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    /**
     *通过token获取关联用户
     */
    public SysUserTokenEntity queryByToken(String token) {
        return sysUserTokenMapper.queryByToken(token);
    }

    /**
     *通过用户ID查询当前用户
     */
    public SysUserEntity queryUser(Long userId){
        return sysUserMapper.getById(userId.intValue());
    }
}
